package com.example.daily.ui.statistics

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.daily.data.dao.FoodRecordDao
import com.example.daily.data.dao.WeightRecordDao
import com.example.daily.data.entity.WeightRecord
import com.example.daily.data.UserPreferences
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZoneOffset
import java.util.*
import javax.inject.Inject

data class StatisticsUiState(
    val weeklyCalories: List<DailyCalories> = emptyList(),
    val totalCalories: Int = 0,
    val averageCalories: Int = 0,
    val mostFrequentFoods: List<FoodFrequency> = emptyList(),
    val foodTypeDistribution: List<FoodTypeData> = emptyList(),
    val weightRecords: List<WeightRecord> = emptyList(),
    val isLoading: Boolean = false,
    val error: String? = null
)

data class DailyCalories(
    val date: String,
    val calories: Int
)

data class FoodFrequency(
    val foodName: String,
    val count: Int,
    val totalCalories: Int
)

data class FoodTypeData(
    val type: String,
    val count: Int,
    val totalCalories: Int,
    val percentage: Float
)

@HiltViewModel
class StatisticsViewModel @Inject constructor(
    private val foodRecordDao: FoodRecordDao,
    private val weightRecordDao: WeightRecordDao,
    private val userPreferences: UserPreferences
) : ViewModel() {
    private val _uiState = MutableStateFlow(StatisticsUiState())
    val uiState: StateFlow<StatisticsUiState> = _uiState

    init {
        observeStatistics()
    }

    private fun observeStatistics() {
        viewModelScope.launch {
            try {
                val userId = userPreferences.getUserId().first()
                    ?: throw IllegalStateException("用户未登录")

                // 获取过去7天的时间范围
                val now = LocalDateTime.now()
                val zoneId = ZoneId.systemDefault()
                val startOfWeek = now.minusDays(6).toLocalDate().atStartOfDay(zoneId).toInstant().toEpochMilli()
                val endOfDay = now.toLocalDate().plusDays(1).atStartOfDay(zoneId).toInstant().toEpochMilli()

                Log.d("StatisticsViewModel", "加载统计数据")
                Log.d("StatisticsViewModel", "当前时间: ${Date()}")
                Log.d("StatisticsViewModel", "开始时间: ${Date(startOfWeek)}")
                Log.d("StatisticsViewModel", "结束时间: ${Date(endOfDay)}")

                // 合并食物记录和体重记录的Flow
                combine(
                    foodRecordDao.getFoodRecordsForUserInTimeRange(
                        userId = userId,
                        startTime = startOfWeek,
                        endTime = endOfDay
                    ),
                    weightRecordDao.getWeightRecordsByDateRange(
                        userId = userId,
                        startTime = startOfWeek,
                        endTime = endOfDay
                    )
                ) { foodRecords, weightRecords ->
                    Log.d("StatisticsViewModel", "获取到食物记录: ${foodRecords.size}条")
                    Log.d("StatisticsViewModel", "获取到体重记录: ${weightRecords.size}条")

                    // 计算每日卡路里
                    val dailyCalories = (0..6).map { daysAgo ->
                        val date = now.minusDays(daysAgo.toLong()).toLocalDate()
                        val startOfDay = date.atStartOfDay(zoneId).toInstant().toEpochMilli()
                        val endOfCurrentDay = date.plusDays(1).atStartOfDay(zoneId).toInstant().toEpochMilli()
                        
                        val calories = foodRecords.filter { record ->
                            record.recordDate in startOfDay until endOfCurrentDay
                        }.sumOf { it.calories }

                        DailyCalories(
                            date = date.toString(),
                            calories = calories
                        )
                    }.reversed()

                    // 计算食物频率
                    val foodFrequency = foodRecords
                        .groupBy { it.foodName }
                        .map { (name, records) ->
                            FoodFrequency(
                                foodName = name,
                                count = records.size,
                                totalCalories = records.sumOf { it.calories }
                            )
                        }
                        .sortedByDescending { it.count }
                        .take(5)

                    // 计算食物类型分布
                    val totalCount = foodRecords.size
                    val foodTypeDistribution = foodRecords
                        .groupBy { getFoodType(it.foodName) }
                        .map { (type, typeRecords) ->
                            FoodTypeData(
                                type = type,
                                count = typeRecords.size,
                                totalCalories = typeRecords.sumOf { it.calories },
                                percentage = typeRecords.size.toFloat() / totalCount
                            )
                        }
                        .sortedByDescending { it.count }

                    // 更新UI状态
                    _uiState.value = _uiState.value.copy(
                        weeklyCalories = dailyCalories,
                        totalCalories = foodRecords.sumOf { it.calories },
                        averageCalories = if (foodRecords.isNotEmpty()) foodRecords.sumOf { it.calories } / 7 else 0,
                        mostFrequentFoods = foodFrequency,
                        foodTypeDistribution = foodTypeDistribution,
                        weightRecords = weightRecords,
                        isLoading = false
                    )
                }.collect()
            } catch (e: Exception) {
                Log.e("StatisticsViewModel", "加载统计数据失败", e)
                _uiState.value = _uiState.value.copy(
                    error = "加载统计数据失败: ${e.message}",
                    isLoading = false
                )
            }
        }
    }

    private fun getFoodType(foodName: String): String {
        // 这里可以根据实际需求扩展食物类型的判断逻辑
        return when {
            foodName.contains("pizza") -> "快餐"
            foodName.contains("nata") -> "甜点"
            foodName.contains("pasteis") -> "主食"
            foodName.contains("tripas") -> "主食"
            foodName.contains("waffles") -> "甜点"
            else -> "其他"
        }
    }
} 